﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace HCommon
{
    public class Sercurity
    {
        private static string EncryptKey = "THAIson@123";

        public static string ConvertToBase64(string strSource)
        {
            Byte[] arrEncodetext = Encoding.Unicode.GetBytes(strSource);
            return Convert.ToBase64String(arrEncodetext);
        }

        public static string ConvertFromBase64(string strSource)
        {
            Byte[] arrPlaintext = Convert.FromBase64String(strSource);
            return Encoding.Unicode.GetString(arrPlaintext);
        }

        public static string Encrypt(string source)
        {
            byte[] keyArray;
            byte[] sourceArray = UTF8Encoding.UTF8.GetBytes(source);

            //Sử dụng Hashing
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(EncryptKey));
            hashmd5.Clear();

            //Không sử dụng Hashing
            //keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(sourceArray, 0, sourceArray.Length);
            tdes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string Decrypt(string source)
        {
            byte[] keyArray;
            byte[] sourceArray = Convert.FromBase64String(source);

            //Sử dụng Hashing
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(EncryptKey));
            hashmd5.Clear();

            //Không sử dụng Hashing
            //keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(sourceArray, 0, sourceArray.Length);

            tdes.Clear();
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}
